package com.ruoyi.web.controller.video;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.ip.URLUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.video.VsDramasVideoEpisodes;
import com.ruoyi.system.service.video.IVsDramasVideoEpisodesService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
/**
 * This file is part of 南阳迈特网络科技有限公司.
 * @company  南阳迈特网络科技有限公司
 * @link     https://www.nymaite.com
 * @document https://product.nymaite.cn
 * @contact  service@nymaite.com
 * @author nymaite
 */
/**
 * 剧集Controller
 * 
 * @author ruoyi
 * @date 2024-04-19
 */
@Api(tags = "剧集信息")
@RestController
@RequestMapping("/video/episodes")
public class VsDramasVideoEpisodesController extends BaseController
{
    @Autowired
    private IVsDramasVideoEpisodesService vsDramasVideoEpisodesService;

    /**
     * 查询剧集列表
     */
//    @ApiOperation("查询剧集列表")
    @CrossOrigin(origins = "*")
    @GetMapping("/list")
    public TableDataInfo list(VsDramasVideoEpisodes vsDramasVideoEpisodes)
    {
//        startPage();
        List<VsDramasVideoEpisodes> list = vsDramasVideoEpisodesService.selectVsDramasVideoEpisodesList(vsDramasVideoEpisodes);
        return getDataTable(list);
    }

    /**
     * 导出剧集列表
     */
//    @ApiOperation("导出剧集列表")
    @Log(title = "剧集", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VsDramasVideoEpisodes vsDramasVideoEpisodes)
    {
        List<VsDramasVideoEpisodes> list = vsDramasVideoEpisodesService.selectVsDramasVideoEpisodesList(vsDramasVideoEpisodes);
        ExcelUtil<VsDramasVideoEpisodes> util = new ExcelUtil<VsDramasVideoEpisodes>(VsDramasVideoEpisodes.class);
        util.exportExcel(response, list, "剧集数据");
    }

    /**
     * 获取剧集详细信息
     */
//    @ApiOperation("获取剧集详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(vsDramasVideoEpisodesService.selectVsDramasVideoEpisodesById(id));
    }

    /**
     * 新增剧集
     */
//    @ApiOperation("新增剧集")
    @Log(title = "剧集", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VsDramasVideoEpisodes vsDramasVideoEpisodes)
    {
        return toAjax(vsDramasVideoEpisodesService.insertVsDramasVideoEpisodes(vsDramasVideoEpisodes));
    }

    /**
     * 修改剧集
     */
//    @ApiOperation("修改剧集")
    @Log(title = "剧集", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VsDramasVideoEpisodes vsDramasVideoEpisodes)
    {
        return toAjax(vsDramasVideoEpisodesService.updateVsDramasVideoEpisodes(vsDramasVideoEpisodes));
    }

    /**
     * 删除剧集
     */
//    @ApiOperation("删除剧集")
    @Log(title = "剧集", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(vsDramasVideoEpisodesService.deleteVsDramasVideoEpisodesByIds(ids));
    }

    /**
     * 推荐剧集列表
     */
    @ApiOperation("推荐剧集列表")
    @CrossOrigin(origins = "*")
    @GetMapping("/recommendList")
    public TableDataInfo recommendList(VsDramasVideoEpisodes vsDramasVideoEpisodes, HttpServletRequest request)
    {
        if (request.getHeader("Lang-Id") != null) {
            Long langId = Long.valueOf(request.getHeader("Lang-Id"));
            vsDramasVideoEpisodes.setLangId(langId);
        } else {
            vsDramasVideoEpisodes.setLangId(65L);
        }
        List<VsDramasVideoEpisodes> list = vsDramasVideoEpisodesService.recommendList(vsDramasVideoEpisodes);
        return getDataTable(list);
    }

    @PostMapping("/increase")
    public AjaxResult increase(@RequestBody VsDramasVideoEpisodes vsDramasVideoEpisodes) {
        int i = vsDramasVideoEpisodesService.increaseEpisodes(vsDramasVideoEpisodes);
        if (i > 0) {
            return success("增加播放量成功！");
        }
        return error("增加播放量失败！");
    }

    @GetMapping("/getList")
    public TableDataInfo getList(VsDramasVideoEpisodes vsDramasVideoEpisodes)
    {
//        startPage();
        List<VsDramasVideoEpisodes> list = vsDramasVideoEpisodesService.getList(vsDramasVideoEpisodes);
        return getDataTable(list);
    }

    @GetMapping("/getEpisodesList")
    public TableDataInfo getEpisodesList(VsDramasVideoEpisodes vsDramasVideoEpisodes)
    {
        startPage();
        List<VsDramasVideoEpisodes> list = vsDramasVideoEpisodesService.getList(vsDramasVideoEpisodes);
        return getDataTable(list);
    }

    @Log(title = "剧集", businessType = BusinessType.EXPORT)
    @PostMapping("/exportLocal")
    public void exportLocal(HttpServletRequest request, HttpServletResponse response, VsDramasVideoEpisodes vsDramasVideoEpisodes) throws Exception
    {
        String[] split = vsDramasVideoEpisodes.getVideo().split(",");
        List<VsDramasVideoEpisodes> list = new ArrayList<VsDramasVideoEpisodes>();
        String baseURl = RuoYiConfig.getUploadPath();
        int i = 1;
        for (String url : split) {
            String file = splitFile(url);
            long videoDuration = getVideoDuration(baseURl + file);
            VsDramasVideoEpisodes episodes = new VsDramasVideoEpisodes();
            episodes.setLangId(65L);
            episodes.setName("第" + i + "集");
            episodes.setDuration(Math.toIntExact(videoDuration));
            episodes.setPrice(0);
            episodes.setVprice(0);
            episodes.setFakeLikes(0);
            episodes.setFakeViews(0);
            episodes.setFakeFavorites(0);
            episodes.setFakeShares(0);
            episodes.setVideo(baseURl + file);
            String s = splitUrl(baseURl + file);
            episodes.setFileRemark(s);
            list.add(episodes);
            i++;
        }
        ExcelUtil<VsDramasVideoEpisodes> util = new ExcelUtil<VsDramasVideoEpisodes>(VsDramasVideoEpisodes.class);
        util.exportExcel(response, list, "剧集数据");
    }

    private String splitFile(String str) {
        int firstSlashIndex = str.indexOf('/');
        int secondSlashIndex = str.indexOf('/', firstSlashIndex + 1);
        int thirdSlashIndex = str.indexOf('/', secondSlashIndex + 1);
        return str.substring(thirdSlashIndex);
    }

    private String splitUrl(String url) {
        // 找到最后一个斜杠的位置
        int lastSlashIndex = url.lastIndexOf('/');
        // 截取从最后一个斜杠之后到字符串末尾的子串
        String substringAfterLastSlash = url.substring(lastSlashIndex + 1);
        // 找到下划线的位置
        int underscoreIndex = substringAfterLastSlash.indexOf('_');
        // 截取下划线之前的部分
        return substringAfterLastSlash.substring(0, underscoreIndex);
    }

    private long getVideoDuration(String videoPath) {
        FFmpegFrameGrabber grabber = null;
        try {
            grabber = new FFmpegFrameGrabber(videoPath);
            grabber.start();

            double frameRate = grabber.getFrameRate();
            long numberOfFrames = grabber.getLengthInFrames();
            long durationInMillis = (long) (numberOfFrames * 1000 / frameRate);
            return durationInMillis / 1000; // Convert to seconds
        } catch (Exception e) {
            throw new RuntimeException("Error calculating video duration.", e);
        } finally {
            if (grabber != null) {
                try {
                    grabber.stop();
                    grabber.release();
                } catch (FrameGrabber.Exception e) {
                    // Handle exception if needed
                    e.printStackTrace();
                }
            }
        }
    }
    @RequestMapping("/importData")
    @ResponseBody
    @ApiOperation("导入数据")
    public AjaxResult importData(@RequestParam MultipartFile file, @RequestParam boolean updateSupport) throws Exception {
        ExcelUtil<VsDramasVideoEpisodes> util = new ExcelUtil<VsDramasVideoEpisodes>(VsDramasVideoEpisodes.class);
        List<VsDramasVideoEpisodes> episodesList = util.importExcel(file.getInputStream());
        int i = vsDramasVideoEpisodesService.batchInsertEpisodes(episodesList);
        if (i > 0) {
            return AjaxResult.success("导入成功");
        } else {
            return AjaxResult.error("导入失败");
        }

    }

}
